<?php
class TopAction extends Action{
    
    public function _initialize()
    {
        Session::set('__APP_KEY', '12081283');
        Session::set('__APP_SECRET', 'af83897e2a14ae245ec16cfe56aa6a67');
        Session::set('__APP_NAME', 'YUANBAO');
        checkLoginSession();
    }    
    
    public function index(){
      
    }
    

public function callBack(){       
if(isset($_GET['top_session']) and (strlen($_GET['top_session'])>16) ){
        $top_session = $_GET['top_session'];
        setcookie('is_login_taobao', $_GET['top_session'], time() + 600 , '/');//生命周期为10分钟        
        Session::set('__Top_Session', $top_session);
        
        echo('淘宝Session已经存储:'.$_SESSION['__Top_Session']);
        //echo (Cookie::get('is_login_taobao'));
        $app_secret = $_SESSION['__APP_SECRET'];                
        $ttrr = $this->_checkSign($_GET['top_sign'],$_GET['top_appkey'],$_GET['top_parameters'],$top_session,$app_secret);
        if($ttrr)
        {        
        echo '淘宝账号验证成功，请关闭窗口';        
        }
        else echo "<br/>非法签名！请重新验证";
      }
 else{
    $top_session = $_GET['top_session'];
    echo "淘宝返回Session有错误：$top_session";
    
    }                    
 }
    
protected function _checkSign($top_sign,$top_appkey,$top_parameters,$top_session,$app_secret){
     $cksign = base64_encode(md5($top_appkey.$top_parameters.$top_session.$app_secret,TRUE));  
    if($cksign==$top_sign)
    {return true;}
    else
    return false;
}
public function deliverysend(){//交易发货
    if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
    if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
        $map['method'] = 'taobao.delivery.send';                
        $map['format'] = 'json';           
        $map['nick'] = 'sandbox_c_1' ;
        //$map['nick'] = $_SESSION['UserInfo']['boss'] ;
        $map['session'] = $_SESSION['__Top_Session'];
        $map['tid'] = $_POST['tid'];
        $map['company_code'] = isset($_POST['company_code'])?$_POST['company_code']:$_SESSION['UserInfo']['defaultExp'];//快递公司代码，如"POST"就代表中国邮政,"ZJS"就代表宅急送.调用 taobao.logistics.companies.get 获取
        $map['out_sid'] = $_POST['out_sid'];//单号
        $map['seller_name'] = $_SESSION['UserInfo']['seller_name'];
        $map['seller_area_id'] = $_SESSION['UserInfo']['seller_area_id'];//卖家所在地国家公布的标准地区码.参考:http://www.stats.gov.cn/tjbz/xzqhdm/t20080215_402462675.htm 或者调用 taobao.areas.get 获取
        $map['seller_address'] = $_SESSION['UserInfo']['seller_address'];
        $map['seller_zip'] = $_SESSION['UserInfo']['seller_zip'];
        $map['seller_phone'] = $_SESSION['UserInfo']['seller_phone'];
        $map['seller_mobile'] = $_SESSION['UserInfo']['seller_mobile'];
        $map['order_type'] = isset($_POST['order_type'])?$_POST['order_type']:'delivery_needed';// delivery_needed(物流订单发货),virtual_goods(虚拟物品发货)
        $map['memo'] = $_POST['memo'];//卖家备注
        $map['fields'] = $_POST['fields'];
        
                
        //$result = $this->_execTop($map,'baseurl');
        $result = $this->_execTop($map);
        //dump($result);
        echo ajaxrt('ok','Server返回结果如下:',$result);
     } 
     else
        {
            echo ajaxrt('error','请登录淘宝');        
        }           
}
public function delistingItem(){//下架商品
    if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
    if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
        $map['method'] = 'taobao.item.update.delisting';                
        $map['format'] = 'json';           
        $map['nick'] = 'sandbox_c_1' ;
        //$map['nick'] = $_SESSION['UserInfo']['boss'] ;
        $map['session'] = $_SESSION['__Top_Session'];
        $map['num_iid'] = $_POST['num_iid'];        
        //$result = $this->_execTop($map,'baseurl');
        $result = $this->_execTop($map);
        //dump($result);
        echo ajaxrt('ok','Server返回结果如下:',$result);
     } 
     else
        {
            echo ajaxrt('error','请登录淘宝');        
        }           
}
public function listingItem(){//上架商品
    if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
    if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
        $map['method'] = 'taobao.item.update.listing';                
        $map['format'] = 'json';           
        $map['nick'] = 'sandbox_c_1' ;
        //$map['nick'] = $_SESSION['UserInfo']['boss'] ;
        $map['session'] = $_SESSION['__Top_Session'];
        $map['num_iid'] = $_POST['num_iid'];
        $map['num'] = 99;
        //$result = $this->_execTop($map,'baseurl');
        $result = $this->_execTop($map);
        //dump($result);
        echo ajaxrt('ok','Server返回结果如下:',$result);
     } 
     else
        {
            echo ajaxrt('error','请登录淘宝');        
        }           
}
public function updateItem(){//更新商品信息
    if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
    if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
        $map['method'] = 'taobao.item.update';                
        $map['format'] = 'json';           
        $map['nick'] = 'sandbox_c_1' ;
        //$map['nick'] = $_SESSION['UserInfo']['boss'] ;
        $map['session'] = $_SESSION['__Top_Session'];
        $map['num_iid'] = '1451883741';
        $map['num'] = 1997;
        $map['title'] = '修改后的商品名称：hi：）';
        $map['price'] = 199.99;
        $map['desc'] = '商品的描述啊描述，25000个字节，1万两千个汉字';
        $map['outer_id'] = 'X0002';
        
        //$result = $this->_execTop($map,'baseurl');
        $result = $this->_execTop($map);
        //dump($result);
        echo ajaxrt('ok','Server返回结果如下:',$result);
     } 
     else
        {
            echo ajaxrt('error','请登录淘宝');        
        }           
}

public function getItem(){//获得商品详情
    if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
    if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
        $map['method'] = 'taobao.item.get';                
        $map['format'] = 'json';           
        $map['nick'] = 'sandbox_c_1' ;
        //$map['nick'] = $_SESSION['UserInfo']['boss'] ; 
        $map['fields'] = 'detail_url,nick,num_iid,title,desc,pic_url,location,num,price,seller_cids,outer_id' ;
        $map['session'] = $_SESSION['__Top_Session'];
        //$map['num_iid'] = '1451883741';
        $map['num_iid'] = $_POST['num_iid'];
        //$result = $this->_execTop($map,'baseurl');
        $result = $this->_execTop($map);
        //dump($result);
        echo ajaxrt('ok','Server返回结果如下:',$result);
     } 
     else
        {
            echo ajaxrt('error','请登录淘宝');        
        }           
}
public function getOnsaleItems(){//搜索店内商品获得概要信息和列表
    if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
    if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
        $map['method'] = 'taobao.items.onsale.get';                
        $map['format'] = 'json';           
        $map['nick'] = 'sandbox_c_1' ;
        $map['seller_cids'] = '1546305,1546310,1547083,1546384' ;
        $map['fields'] = 'title,nick,num_iid,pic_url,num,price,seller_cids,outer_id' ;
        $map['session'] = $_SESSION['__Top_Session'];         
        //$map['nick'] = $_SESSION['UserInfo']['boss'] ;        
                    
        //$result = $this->_execTop($map,'baseurl');
        $result = $this->_execTop($map);
        //dump($result);
        echo ajaxrt('ok','Server返回结果如下:',$result);
     } 
     else
        {
            echo ajaxrt('error','请登录淘宝');        
        }           
}
public function getShopCat(){//获得最新的店铺显示分类返回的是json，客户端组装为td的htmlstr           
    //$map['method'] = 'taobao.shopcats.list.get';
    $map['method'] ='taobao.sellercats.list.get';               
    $map['format'] = 'json';           
    $map['nick'] = 'sandbox_c_1' ;     
    //$map['nick'] = $_SESSION['UserInfo']['boss'] ;
         
    //$result = $this->_execTop($map,'baseurl');
    $result = $this->_execTop($map);
    //dump($result);
    echo ajaxrt('ok','Server返回结果如下:',$result);

}

public function getLatestOrder(){//获得增量的卖出订单，以往订单从本地数据库查询
        $status = $_POST['status'] ;        
        if($_COOKIE['is_login_taobao']) {$_SESSION['__Top_Session'] = $_COOKIE['is_login_taobao'];}
        if(isset($_SESSION['__Top_Session']) and ($_SESSION['__Top_Session']!='')) {
            
            $map['status'] = $status ;
            
            $map['session'] = $_SESSION['__Top_Session'];            
            $map['method'] = 'taobao.trades.sold.increment.get';            
            $map['format'] = 'json';            
            $map['fields'] = 'tid,alipay_no,total_fee,created,receiver_name,receiver_address,receiver_mobile,receiver_phone,
            seller_memo,seller_nick,buyer_nick,status,orders.title,orders.oid,orders.price,orders.num' ;            
            $map['start_modified'] = date('Y-m-d H:i:s',time()-24*60*60);
            $map['end_modified'] = date('Y-m-d H:i:s');            
            $map['nick'] = 'sandbox_c_1' ;
            //$map['nick'] = $_SESSION['UserInfo']['boss'] ;
            
            $result = $this->_execTop($map);
            //dump($result);            
            $arr = json_decode($result,true);
            //dump($arr);
            if(isset($arr['trades_sold_increment_get_response']) )
            {
                  //dump(isset($arr['trades_sold_increment_get_response']));
                if(isset($arr['trades_sold_increment_get_response']['total_results']) )       
                {
                    //查询每个tid对应的fullinfo，获得客户email和备注，卖家备注,商品自有编码
                    $tradecnt = $arr['trades_sold_increment_get_response']['total_results'];
                    while($tradecnt>0)
                    {
                    $map['status'] = $status ;
                    $mapx['app_key'] = $_SESSION['__APP_KEY'] ;
                    $mapx['session'] = $_SESSION['__Top_Session'];            
                    $mapx['method'] = 'taobao.trade.fullinfo.get';            
                    $mapx['format'] = 'json';                         
                     $mapx['tid'] =   $arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['tid'];
                     $mapx['fields'] ='seller_memo,alipay_no,orders.outer_iid,buyer_message,orders.oid,buyer_email';//buyer_message 取代buyer_memo
                     $resultx = $this->_execTop($mapx);
                     $arrx = json_decode($resultx,true);
                     //dump($arrx);
                     $tddx = $arrx['trade_fullinfo_get_response']['trade'];
                     $arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['seller_memo'] =isset($tddx['seller_memo'])?$tddx['seller_memo']:NULL;
                     $arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['buyer_message'] =isset($tddx['buyer_message'])?$tddx['buyer_message']:NULL;
                     $arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['alipay_no'] =isset($tddx['alipay_no'])?$tddx['alipay_no']:NULL;
                     $arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['buyer_email'] =isset($tddx['buyer_email'])?$tddx['buyer_email']:NULL;                     
                     $ordcntt = count($arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['orders']['order']);
                     //dump($arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['orders']['order']);
                     while($ordcntt>0)
                     {
                        //dump($tddx['orders']['order'][$ordcntt-1]);
                        $arr['trades_sold_increment_get_response']['trades']['trade'][$tradecnt-1]['orders']['order'][$ordcntt-1]['outer_iid'] =isset($tddx['orders']['order'][$ordcntt-1]['outer_iid'])?$tddx['orders']['order'][$ordcntt-1]['outer_iid']:NULL;
                        $ordcntt = $ordcntt -1;                     }
                     $tradecnt = $tradecnt -1;   
                    }
                    $trrtt = addToLocalOrd($arr);    
                    if($trrtt) {echo ajaxrt('ok','同步'.$arr['trades_sold_increment_get_response']['total_results'].'条数据成功',$result);}
                    else
                    {
                        echo ajaxrt('ok','缓存增量订单记录出错',$result);
                    }                
                }
                else
                {   
                   echo ajaxrt('ok','最近24小时没有新增订单!',$result); 
                }
            }
            else
            {
                echo ajaxrt('error','同步数据出错: '.$arr['error_response'],$result);
            }
        }    
        else
        {
            echo ajaxrt('error','请登录淘宝');        
        }        
    }

protected function  _execTop($map,$urlkind=NULL){
        $baseurltest ='http://gw.api.tbsandbox.com/router/rest?';
        $baseurl ='http://gw.api.taobao.com/router/rest?';    
        $map['v'] = '2.0';
        $map['timestamp'] = date('Y-m-d H:i:s') ;
        $map['sign_method'] =  'md5';
        $map['app_key'] = $_SESSION['__APP_KEY'] ;
        //$map['sign_method'] =  'HmacMD5';
        $paramArr = $map;
        $appSecret = $_SESSION['__APP_SECRET'];
            $sign = createSign($paramArr,$appSecret);
            $strParam = createStrParam($paramArr);
            $strParam .= 'sign='.$sign;
            $url = isset($urlkind)?($baseurl.$strParam):($baseurltest.$strParam);//测试url，可更换为正式url
            $result = file_get_contents($url);  
            setcookie('is_login_taobao', $_SESSION['__Top_Session'], time() + 600*2,'/');//延长寿命20分钟             
            return $result;
    }    
}
?>